package com.mine.frame.mylandemo.ui.jiecang

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import android.util.Log
import android.view.MotionEvent
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.forick.Panel3In1Adapter
import com.mine.frame.mylandemo.entity.forick.ControlBean
import com.mine.frame.mylandemo.mvp.iview.ILiftCabinet
import com.mine.frame.mylandemo.mvp.presenter.LiftCabinetPresenter
import com.mine.frame.mylandemo.ui.dialog.LoadingDialog
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.MGSerialPort
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.service.MGSocketService
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.atv_forick_panel_3in1.*
import kotlinx.android.synthetic.main.atv_forick_panel_3in1.mRecycler
import kotlinx.android.synthetic.main.atv_jiecang_translation.*
import kotlinx.android.synthetic.main.layout_connect.*
import java.util.concurrent.TimeUnit

/**
 * @Date 2022/2/12
 * Description:
 * 波特率：9600
 */
@SuppressLint("SetTextI18n")
class LiftCabinetAtv : BaseActivity<ILiftCabinet, LiftCabinetPresenter>(),
    ILiftCabinet,
    MGNettyConnectListener {
    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233


    private val mAdapter by lazy { Panel3In1Adapter() }

    override fun initLayoutId(): Int = R.layout.atv_jiecang_lift_cabinet

    override fun initPresenter(): LiftCabinetPresenter = LiftCabinetPresenter(this)

    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(tvInfo).setMessage("正在连接服务器...").showSuccess()
                MGSocketService.get().setListener(this@LiftCabinetAtv)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        connectAndDisconnect()
        initRecycler()
        mPresenter.createControlData()
    }


    /**
     * 连接和取消连接
     */
    private fun connectAndDisconnect() {
        ClickUtils.applySingleDebouncing(arrayOf(btnConnect, btnDisconnect)) {
            when (it.id) {
                R.id.btnConnect -> {
                    KeyboardUtils.hideSoftInput(this)
                    if (edtIP.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    } else {
                        ipStr = edtIP.text.toString()
                    }


                    if (edtPort.text.isNullOrEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    } else {
                        port = edtPort.text.toString().toInt()
                        if (port < 1 || port > 65535) {
                            SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipStr.isEmpty()) {
                        SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }

                    initSocket()
                }
                R.id.btnDisconnect -> {
                    MGSocketService.get().disconnect(ipStr, port)
                }
            }
        }

    }


    override fun onStart() {
        super.onStart()
        if (!MGSocketService.get().isBind) {
            ServiceUtils.bindService(
                MGSocketService::class.java,
                serviceConnect,
                Service.BIND_AUTO_CREATE
            )
        }
    }


    /**
     * 创建Socket连接
     */
    private fun initSocket() {
        MGSocketService.get().connectNetty(ipStr, port)
    }


    /**
     * 更新指示器
     */
    private fun updateIndicator(connect: Boolean) {
        val resId = if (connect) {
            R.drawable.blue_circle
        } else {
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }

    override fun onDestroy() {
        if (MGSocketService.get().isBind) {
            ServiceUtils.unbindService(serviceConnect)
        }
        super.onDestroy()
    }

    private fun initRecycler() {
        mRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener { _, _, position ->
            val controlBean = mAdapter.data[position]
            if (!controlBean.isHeader) {
                controlBean.command?.let {
                    //MGSocketService.get().write(ipStr ,port ,it)
                    MGSocketService.get().write(ipStr, port, it)
                } ?: let {
                    SnackbarUtils.with(btnConnect).setMessage("指令未空").showWarning(true)
                }
            }
        }
    }




    override fun connectBack(ip: String, port: Int) {
        updateIndicator(true)
    }

    override fun disconnectBack(ip: String, port: Int) {
        updateIndicator(false)
    }


    override fun readBack(ip: String, port: Int, result: ByteArray) {
        SnackbarUtils.with(btnConnect).setMessage("收到消息").showSuccess(true)
        tvInfo.text = "接收:${result.toHexString(true)}"

    }

    override fun writeBack(ip: String, port: Int, successful: Boolean, data: ByteArray) {
        if (successful) {
            SnackbarUtils.with(btnConnect).setMessage("发送成功").showSuccess(true)
        } else {
            SnackbarUtils.with(btnConnect).setMessage("发送失败").showError(true)
        }
    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {
        error.message?.let {
            showErr(it)
        }
    }

    override fun initControlList(data: MutableList<ControlBean>) {
        mAdapter.setList(data)
    }

}